package club.calong.sanniu.service;

import club.calong.sanniu.pojo.Permission;
import club.calong.sanniu.pojo.Role;
import club.calong.sanniu.pojo.User;
import club.calong.sanniu.repository.PermissionRepository;
import club.calong.sanniu.repository.RoleRepository;
import club.calong.sanniu.repository.UserRepository;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

@Service
public class SysUserDetailsServiceImpl implements UserDetailsService {

	private final UserRepository URepository;
	private final RoleRepository RRepository;
	private final PermissionRepository PRepository;

	public SysUserDetailsServiceImpl(UserRepository URepository,
									 RoleRepository RRepository,
									 PermissionRepository PRepository
	) {
		this.URepository = URepository;
		this.RRepository = RRepository;
		this.PRepository = PRepository;
	}

	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

		// 根据用户名查询数据库
		QueryWrapper<User> wrapperU = new QueryWrapper<>();
		wrapperU.eq(User.USERNAME, username);
		User user = URepository.selectOne(wrapperU);

		if (user != null) {
			// 查询权限
			QueryWrapper<Role> wrapperR = new QueryWrapper<>();
			wrapperR.in(Role.ID, user.getRoles());
			List<Role> roles = RRepository.selectList(wrapperR);
			List<String> auths = new ArrayList<>(roles.size());
			roles.forEach(role -> {
				user.addRoleName(role.getName());
				QueryWrapper<Permission> wrapperP = new QueryWrapper<>();
				wrapperP.in(Permission.ID, role.getPermissions());
				List<Permission> permissions = PRepository.selectList(wrapperP);
				permissions.forEach(item -> {
					auths.add(item.getName());
				});
			});
			if (!CollectionUtils.isEmpty(auths)) {
				user.setAuthorities(auths);
			}
		}
		return user;
	}
}
